import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
var QRCode = require('qrcode.react');
import { Modal, message,Table,Dropdown,Menu,Button,Input ,Row,Col,Select,Popconfirm,Switch} from 'antd';
const Search = Input.Search;
const Option = Select.Option;
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import api from '../api';
import moment from 'moment';
import {bind_change} from '../common/State';

import {CHANNEL_TYPE} from '../constants/index';


export default class Channel extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
           page:1,
           total:1,
           pageSize:10,
           list:[],
           loading:true,
           ermModal:false
        };
    }

    componentWillMount(){
        this.doFetch();
    }
    componentWillReceiveProps(nextProps){
        //  this.doFetch({type});
    }
    async doFetch(page=1){

      let result = await api('/generalize/channel/list',{page});

      if(result.cd!=0){
        message.error(result.msg);
        this.setState({loading:false})
        return;
      }
      this.setState({
          page,
          total:result.total,
          list:result.data,
          loading:false
      })
    }


    //删除事件
    async deleteById(record){
       let result =  await api('/generalize/channel/delete',{id:record.id});
       if(result.cd !=0 ){
         message.error(result.msg);
         return;
       }
        message.success('删除成功',1,() => {
          let {page,list,type} = this.state;
          if(list.length==1&&page>1){page--}
          this.doFetch(page)
        })
    }
    

    //分页
    toPage({current:page,pageSize,total}){
      this.setState({loading:true})
      this.doFetch(page);
    }

    //状态事件
    async switchChange(record){
      let result = await api('/generalize/channel/updateIntroducerStatus',{id:record.id,status:!record.status});
      if(result.cd!=0){
        message.error(result.msg);
        return;
      }
      this.setState({loading:true})
      let {type,page} = this.state;
      this.doFetch(page,type);
    }

    //请求二维码
    async requestQrcodeStr(record){
      let result = await api('/weixin/product/qrcodeStr' , {id:record.id});
      if(result.qrcodeStr){
        this.setState({
          ermModal:true,
          qrcodeStr:result.qrcodeStr
        })
      }
    }

   
    render() {
        var {list, page,total,pageSize,loading}=this.state;
        return (
            <div >
                <NavBar navs={[{title:`渠道管理`}]} />
                <ContentBody className='container'>

                  <div className='marginB10'>
                      <Button 
                        type="primary" 
                        onClick={()=>{
                          this.context.router.push(`/generalize/channel/edit`)
                        }}
                      >
                        创建新渠道
                      </Button>
                  </div>  

                  <Table 
                    bordered
                    columns={this.getColumns()} 
                    simple 
                    dataSource={list}
                    pagination={{
                      current:page,
                      total,
                      pageSize,
                      showQuickJumper : true
                    }}
                    loading={loading}
                    onChange={this.toPage.bind(this)}
                    scroll={{ x: 1000 }}
                    rowKey={(record,index) => index}
                  />
                </ContentBody>

                <Modal
                  title="微信扫一扫"
                  visible={this.state.ermModal}
                  width={300}
                  onCancel = {()=>{
                    this.setState({ermModal:false})
                  }}
                  footer={[
                    <Button onClick={()=>{
                      this.setState({ermModal:false})  
                    }}>关闭</Button>
                  ]}
                >
                  <div style={{width:'200px',margin:'auto'}}>
                    {/* <QRCode value={`http://yfq.tqblog.cn/h5/register?beInviteCode=${this.state.qrcodeStr}`} size={200}/>  */}
                    <QRCode value={`${this.state.qrcodeStr}`} size={200}/> 
                  </div>
                </Modal>
            </div>
        );
    }

    getColumns(){

      let columns = [
            {
              title: '渠道ID',
              dataIndex: 'id',
              key: 'id',
            }, {
              title: '渠道类型',
              dataIndex: 'type',
              key: 'type',
              render:(type,record) => {
                 return CHANNEL_TYPE[type] 
              }
            }, {
              title: '渠道名称',
              dataIndex: 'name',
              key: 'name'
            }, {
              title: '渠道手机号',
              dataIndex: 'phone',
              key: 'phone'
            }, {
              title: '渠道所属机构',
              dataIndex: 'organization',
              key: 'organization'
            }, {
              title: '渠道专属二维码',
              dataIndex: 'qrcode',
              key: 'qrcode',
              render:(qrcode,record) => {
                if(qrcode){
                  return (
                    <a 
                      href='javascript:void 0;' 
                      onClick={() => {
                        this.setState({
                          ermModal:true,
                          qrcodeStr:qrcode
                        })
                      }}
                    >查看二维码</a>
                  )
                }else{
                  return (
                    <a 
                      href='javascript:void 0;' 
                      onClick={this.requestQrcodeStr.bind(this,record)}
                    >查看二维码</a>
  
                    )
                }
                
              }
            }, {
              title: '渠道归属',
              dataIndex: 'employeeName',
              key: 'employeeName'
            }, {
              title: '创建时间',
              dataIndex: 'created_at',
              key: 'created_at'
            },{
              title: '操作',
              key: 'action',
              fixed: 'right',
              width:100,
              render: (record) =>{
                  return (
                        <span>
                          <a 
                            href='javascript:void 0'
                            onClick={()=>{
                              this.context.router.push(`/generalize/channel/edit?id=${record.id}`)
                            }}
                          >
                          编辑
                          </a>
                          <span className="ant-divider" />
                          <Popconfirm 
                            title="确定要删除?" 
                            onConfirm={this.deleteById.bind(this,record)} 
                            okText="确定" 
                            cancelText="取消"
                          >
                            <a href='javascript:void 0'>删除</a>
                          </Popconfirm>
                        </span>
                      )
              } ,
            }
        ];

        return columns
    }
}

Channel.contextTypes= { router: React.PropTypes.object.isRequired};

